package study.convertxml;

import cn.hutool.core.util.XmlUtil;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Document;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

public class JavaToxml {
    public static void javaToxml(Report report) throws Exception {
        // 获取JAXB的上下文环境，需要传入具体的 Java bean -> 这里使用Student
        JAXBContext context = JAXBContext.newInstance(Report.class);
        StringWriter writer = new StringWriter();
        // 创建 Marshaller 实例
        Marshaller marshaller = context.createMarshaller();
        // 设置转换参数 -> 这里举例是告诉序列化器是否格式化输出
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        // 构建输出环境 -> 这里使用标准输出，输出到控制台Console
        //PrintStream out = System.out;
        //marshaller.marshal(report, out);
        // 将所需对象序列化 -> 该方法没有返回值
        marshaller.marshal(report, writer);
        String xmlStr = writer.toString();
        xmlStr = StringUtils.replace(xmlStr, "&quot;", "'");
        System.out.println(xmlStr);
        Document d = XmlUtil.beanToXml(report);
        d.setXmlStandalone(true);
        System.out.println(XmlUtil.format(d));
    }

    public static void main(String[] args) throws Exception {
        Item item = new Item();
        item.setClch("clch");
        item.setJxdw("jxdw");
        item.setXjcz("333");
        item.setJxxc("444");
        item.setClcx("ddddd");
        item.setXjsj("5555");
        Item item1 = new Item();
        item1.setClch("999clch");
        item1.setJxdw("999jxdw");
        item1.setXjcz("999333");
        item1.setJxxc("999444");
        item1.setClcx("999ddddd");
        item1.setXjsj("9995555");
        List<Item> itemList = new ArrayList<Item>();
        itemList.add(item1);
        itemList.add(item);
        Xjxx xjxx = new Xjxx();
        xjxx.setItem(itemList);
        Base base = new Base();
        base.setBgbb("1");
        base.setBgbs("2");
        base.setBgsj("3");
        base.setBgzm("4");
        base.setBwcd("5");
        base.setBwmc("6");
        base.setCzbz("7");
        base.setSjbs("8");
        Report report = new Report();
        report.setBase(base);
        report.setXjxx(xjxx);
        javaToxml(report);
    }
}
